package com.xiaotao.es.config;

import com.xiaotao.es.config.properties.EsProperties;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author xiaotao
 */
@Configuration
public class ElasticSearchConfig {

    @Resource
    private EsProperties esProperties;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "123456"));
        return new RestHighLevelClient(RestClient.builder(HttpHost.create(getAddress()))
                .setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(basicCredentialsProvider)));
    }

    private String getAddress(){
        return  esProperties.getUrl() + ":" + esProperties.getPort();
    }
}
